package org.example.common.redis.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.example.common.core.constants.CacheConstants;
import org.example.common.core.constants.Constants;
import org.example.common.core.constants.TenantConstants;
import org.example.common.core.domain.model.LoginModel;
import org.example.common.core.domain.model.LoginUser;
import org.example.common.core.utils.ServletUtils;
import org.example.common.core.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;

public class LoginHelper {

    /**
     * 获取用户身份信息
     * @return 用户信息
     */
    public static LoginUser getLoginUser()
    {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public static LoginUser getLoginUser(HttpServletRequest request)
    {
        try {
            // 获取请求携带的令牌
            String token =request.getHeader(Constants.AUTHORIZATION_TOKEN_HEADER);
            if (StringUtils.isNotEmpty(token))
            {
                //解密
                String json = Base64.decodeStr(token);
                JSONObject jsonObject = JSON.parseObject(json);
                String authToken= jsonObject.getString(Constants.UUID);
                String tenant_id= jsonObject.getString(Constants.TENANT_ID);
                String grant_user= jsonObject.getString(Constants.GRANT_USER);
                String device_type= jsonObject.getString(Constants.DEVICE_TYPE);
                LoginUser loginUser= RedisUtils.getCacheObject(String.format(CacheConstants.LOGIN_TOKEN_KEY,
                        tenant_id,grant_user,device_type,authToken));
                return loginUser;
            }
            return null;
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 退出登录
     * @return
     */
    public static boolean logout(){

        return logout(ServletUtils.getRequest());
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    public static boolean logout(HttpServletRequest request)
    {
        try{
            // 获取请求携带的令牌
            String token =request.getHeader(Constants.AUTHORIZATION_TOKEN_HEADER);
            if (StringUtils.isNotEmpty(token))
            {
                //解密
                String json = Base64.decodeStr(token);
                JSONObject jsonObject = JSON.parseObject(json);
                String authToken= jsonObject.getString(Constants.UUID);
                String tenant_id= jsonObject.getString(Constants.TENANT_ID);
                String grant_user= jsonObject.getString(Constants.GRANT_USER);
                String device_type= jsonObject.getString(Constants.DEVICE_TYPE);
                Integer expires_in= jsonObject.getInteger(Constants.EXPIRES_IN);
                RedisUtils.setCacheObject(String.format(CacheConstants.TOKEN_BLACK_KEY,tenant_id,authToken),authToken,
                        Duration.ofSeconds(expires_in));
                RedisUtils.setCacheObject(String.format(CacheConstants.LOGIN_TOKEN_KEY,tenant_id,grant_user,device_type,authToken),authToken,
                        Duration.ofSeconds(expires_in));
                return true;
            }
            return false;
        }catch (Exception e){
            return false;
        }
    }


   public static Long getUserId(){
       if( checkLogin())
       {
           LoginUser loginUser= getLoginUser();
           return loginUser.getUserId();
       }
        return null;
   }

   public static String getTenantId(){
       if(checkLogin())
       {
           LoginUser loginUser= getLoginUser();
           return loginUser.getTenantId();
       }
       return null;
   }

   public static boolean checkLogin(){
        if(ServletUtils.getRequest()!=null)
        {
            LoginUser loginUser= getLoginUser();
            if(ObjectUtil.isNotEmpty(loginUser)){
                return true;
            }
        }
        return false;
   }

    /**
     * 超级管理员
     * @return
     */
    public static boolean isSuperAdmin() {
        LoginUser loginUser=  getLoginUser();
        if(ObjectUtil.isNull(loginUser)) return false;
        return loginUser.isSuperAdmin();
    }

    /**
     * 超级管理员
     * @return
     */
    public static boolean isSuperAdmin(Long userId) {
        return TenantConstants.SUPER_ADMIN_ID.equals(userId);
    }
    /**
     * 租户管理员
     * @return
     */
    public static boolean isTenantAdmin() {
        LoginUser loginUser=  getLoginUser();
        if(ObjectUtil.isNull(loginUser)) return false;
        return loginUser.isTenantAdmin();
    }

    public static void login(LoginUser loginUser, LoginModel loginModel) {
        loginUser.setToken(loginModel.getToken());
        loginUser.setExpires_in(loginModel.getTimeout());
        loginUser.setToken(loginModel.getToken());
        RedisUtils.setCacheObject(String.format(CacheConstants.LOGIN_TOKEN_KEY,
                        loginUser.getTenantId(),
                        loginModel.getGrantUser(),loginModel.getDevice(),loginUser.getToken()),
                loginUser,Duration.ofSeconds(loginModel.getTimeout()));
        RedisUtils.setCacheObject(String.format(CacheConstants.LOGIN_ACCOUNT_KEY,
                        loginUser.getTenantId(),
                        loginModel.getGrantUser(),
                        loginModel.getDevice(),
                        loginUser.getUsername()),
                loginUser.getToken(), Duration.ofSeconds(loginModel.getTimeout()));
    }
}
